package org.indi.graduatemanagement.controller;


import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.indi.graduatemanagement.common.lang.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

@RestController
@RequiresAuthentication
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf('.'));
        String newFileName = new Date().getTime() + suffix;
        String path = "D:\\upload\\";
        File newFile = new File(path + newFileName);
        try {
            file.transferTo(newFile);
            return Result.successful(newFileName);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("上传失败");
        }
    }

    @GetMapping("/{filename}")
    public void downloadFile(@PathVariable("filename") String filename, HttpServletRequest request, HttpServletResponse response) {
        File file = new File("D:\\upload\\", filename);
        try (InputStream inputStream = new FileInputStream(file);
             OutputStream outputStream = response.getOutputStream();) {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/delete/{filename}")
    @RequiresPermissions("delete")
    @RequiresAuthentication //登录后可查询
    public Result deleteFile(@PathVariable("filename") String filename) {
        File file = new File("D:\\upload\\", filename);
        if (file.delete()) {

            return Result.successful("删除成功");
        } else {
            return Result.successful("文件不存在");
        }
    }
}
